<?php

namespace App\Services\UserUpgrade;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserUpgrade
{
	protected ?User $user = null;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

	protected function execute(User $user)
	{
        if ($user->is_mock) return;

        if ($user->is_gold_intern and $user->is_gold_master) return;

        DB::transaction(function () use ($user) {

            $isIntern = $user->isValidGoldIntern();
            $isMaster = $user->isValidGoldMaster();

            if ($isIntern and $isMaster) {
                if ($user->is_gold_master) return;
                $reason = '升级为正式炼金师';
            } elseif ($isIntern and !$isMaster) {
                if ($user->is_gold_intern) return;
                $reason = '升级为见习炼金师';
            } else {
                $reason = '';
            }

            $user->upgradeLogs()->create(['reason' => $reason]);
            $user->update(['is_gold_intern' => $isIntern, 'is_gold_master' => $isMaster]);
        });

	}

	public function upgrade(User $user)
	{
		$this->execute($user);

        if (! $user->parent) return;
		$this->execute($user->parent);
	}
}
